﻿using System;
using System.Collections.Generic;
using Microsoft.Practices.Unity;
using VisualWip.Core;
using VisualWip.Core.Interfaces;

namespace VisualWip.Util
{
    public class ViewModelFactory : IViewModelFactory
    {
        private readonly IUnityContainer _container;
        private readonly List<ViewModelFactoryHandler> _settingsViewModelHandlers;
        private readonly List<ViewModelFactoryHandler> _viewModelHandlers;

        public ViewModelFactory(IUnityContainer container)
        {
            _container = container;
            _viewModelHandlers = new List<ViewModelFactoryHandler>();
            _settingsViewModelHandlers = new List<ViewModelFactoryHandler>();
        }

        #region IViewModelFactory Members

        public void RegisterViewModel<TType, TViewModel>()
        {
            _viewModelHandlers.Add(ViewModelFactoryHandler.Create<TType, TViewModel>());
        }

        public void RegisterSettingsViewModel<TType, TSettingsViewModel>()
        {
            _settingsViewModelHandlers.Add(ViewModelFactoryHandler.Create<TType, TSettingsViewModel>());
        }


        public TViewModel CreateViewModel<TViewModel>(object model)
            where TViewModel : class
        {
            return CreateViewModel(model) as TViewModel;
        }

        public object CreateViewModel(object model)
        {
            return CreatViewModel(_viewModelHandlers, model);
        }

        public TSettingsViewModel CreateSettingsViewModel<TSettingsViewModel>(object model)
            where TSettingsViewModel : class
        {
            return CreateSettingsViewModel(model) as TSettingsViewModel;
        }

        public object CreateSettingsViewModel(object model)
        {
            return CreatViewModel(_settingsViewModelHandlers, model);
        }

        #endregion

        private object CreatViewModel(IEnumerable<ViewModelFactoryHandler> viewModelFactoryHandlers, object model)
        {
            foreach (ViewModelFactoryHandler registryEntry in viewModelFactoryHandlers)
            {
                if (registryEntry.Match.Invoke(model))
                {
                    return
                        _container.Resolve(registryEntry.ViewModel,
                                           new DependencyOverride(registryEntry.Model, model));
                }
            }

            //TODO: Add Convenstion matching
            throw new NotImplementedException();
        }
    }
}